<script setup lang='ts'>
import {
  FetchLatestValueByDeviceType,
  GetHandHeldRecordList
} from '@/api/publicApi'
import { ref, onMounted } from 'vue'
import * as signalR from '@microsoft/signalr'
import localforage from 'localforage'
import setUpTime from '@/utils/setUpTime'
import MeasurePointDetail from '@/components/global/MeasurePointDetail.vue'
import { addImg, localForageImg } from '@/utils/common'
defineProps({
  deviceType: {
    type: String,
    default: ''
  }
})

// 表格
const tableDatas = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-02',
    name: 'aaaa',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-04',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'bbbbb',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'cccc',
    address: 'No. 189, Grove St, Los Angeles'
  },
  {
    date: '2016-05-01',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  }
]

// refs
const measurePointDetailRef = ref()

const cellStyle = {
  textAlign: 'center'
}

const headStyle = {
  textAlign: 'center'
}

// 定义变量
// 表格数据
const tableData:any = ref([])
// 
const holdDeviceList: any = ref([])
// 展示的图标名称
const showImageName = ref('')
// 图片地址
const imgURL:any = ref('')

// 定义函数 
onMounted(async () => {
  // 获取设备测点实时数据
  var connection:any = new signalR.HubConnectionBuilder().withUrl('/all/signalr', {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets
  })
    .build()
  connection.start()
  connection.on('updateTemperShock', message => {
    // 接收signalr数据
    let {
      BarWheelMachineCode,
      MeasurePointCode,
      IsError,
      LastModificationTime,
      ShockValue,
      TemperValue
    } = JSON.parse(message)

    if (BarWheelMachineCode === localStorage.BarWheelMachineCode) {
      tableData.value.forEach(item => {
        if (item.measurePointCode === MeasurePointCode) {
          (item.shockValue = ShockValue),
          (item.temperValue = TemperValue),
          (item.isError = IsError),
          (item.lastModificationTime =
              setUpTime.formatTime(LastModificationTime))
        }
      })
    }

    // 按时间排序
    tableData.value.sort(function (a, b) {
      return b.lastModificationTime < a.lastModificationTime
    })
  })
  connection.onclose(() => setTimeout(connection.start(), 5000))
  //  this.getHistoryList();
  getBeltMotor()
  showImageName.value = '皮带电机'
  imgURL.value = await localforage.getItem(showImageName.value) as string
  if (imgURL.value instanceof Blob) {
    addImg(showImageName, 'imgContainer')
  } else {
    // 没有缓存：请求图片添加到缓存里  这里必须使用require传递图片路径
    // await localForageImg(require('@/assets/equipment/' + showImageName.value + '.png'), showImageName)
    // await localForageImg(getImg(showImageName.value), showImageName)
    // 获取缓存中的图片
    addImg(showImageName, 'imgContainer')
  }
  // console.log('设备类型----->', deviceType)
  
})

const  getBeltMotor = () => {
  console.log('加载时获取实时列表数据----------->')
  let DeviceTypeList = JSON.parse(localStorage.DeviceTypeList)
  let DeviceTypeObj = DeviceTypeList.find(
    item => item.name === '皮带电机'
  )
  let params = {
    BarWheelMachineCode: localStorage.BarWheelMachineCode,
    BwmCode: localStorage.BarWheelMachineCode,
    DeviceTypeCode: DeviceTypeObj.code
  }
  // 加载时获取实时列表数据
  FetchLatestValueByDeviceType(params).then(res => {
    if (res.success === true) {
      tableData.value = res.result
      tableData.value.forEach(item => {
        item.lastModificationTime = setUpTime.formatTime(
          item.lastModificationTime
        )
      })
    }
    console.log('加载时获取实时列表数据----------->',res)
  })
  GetHandHeldRecordList(params).then(res => {
    holdDeviceList.value = res.result.items
    holdDeviceList.value[0].lastModificationTime = setUpTime.formatTime(holdDeviceList.value[0].lastModificationTime)
  })
}

// 展示测点详情
const showMeasurePointDetail = (row:any) => {
  measurePointDetailRef.value.showDialog(row)
}

// 引入静态资源
const getImg = (name:string) => {
  return new URL(`@/assets/equipment/' + ${name} + '.png'`, import.meta.url).href
}
</script>

<template>
  <el-table
    :cell-style="cellStyle"
    :header-cell-style="headStyle"
    :data="tableDatas"
    max-height="100%"
  >
    <el-table-column
      prop="date"
      label="传感测点"
    >
      <template #default="scope">
        <div
          class="point-box"
          @click="showMeasurePointDetail(scope.row)"
        >
          {{ scope.row.date }}(温度/振动)
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="name"
      label="值"
    >
      <template #default="scope">
        <div class="value-box">
          <div>振动值：{{ scope.row.shockValue }} (m/s²)</div>
          <div>温度值：{{ scope.row.temperValue }} (°C) </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="address"
      label="状态"
    >
      <template #default="scope">
        <div class="status-main-box">
          <div
            :id="(scope.row.name === 'Tom') ? '' : ((scope.row.name === 'aaaa') ? 'firstLevel' : 'secondLevel') "
            class="status-box"
          />
        </div>
      </template>
    </el-table-column>
    <el-table-column
      prop="address"
      label="更新时间"
    />
  </el-table>
  <MeasurePointDetail ref="measurePointDetailRef" />
</template>

<style scoped lang=scss>
.point-box {
  &:hover {
    cursor: pointer;
  }
}

.production-statistics-main-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #fff;

  .tabs-box {
    width: 98%;
    height: 96%;

    /* border: 1px solid red; */
    box-shadow: #dbd9d9 0 0 0 1px;
  }
}

.value-box {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  height: 100%;

  >div {
    width: 100%;
  }
}

.status-main-box {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;

  .status-box {
    width: 167px;
    height: 30px;
    background-color: #22f34c;
  }
}

/* stylelint-disable-next-line selector-id-pattern */
#firstLevel {
  background-color: #ede215;
}
/* stylelint-disable-next-line selector-id-pattern */
#secondLevel {
  background-color: #fe0808;
}
</style>